import React, {
  forwardRef,
  useRef,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";

/**
 * forwardRef 获取子组件中某个元素的ref
 * useImperativeHandle 暴露子组件中的方法给父组件使用
 */

const Child = forwardRef<any, any>((props, ref) => {
  const [text, setText] = useState("你好世界");
  const submit = () => {
    setText("你好");
  };
  useImperativeHandle(ref, () => {
    return {
      text,
      submit,
    };
  });

  return <div ref={ref}>{text}</div>;
});

const RefHooks = () => {
  const childRef = useRef<any>(null);
  useEffect(() => {
    console.log(childRef.current, "-");
    childRef.current?.submit();
  });
  return <Child ref={childRef} title="Child" />;
};

export default RefHooks;
